package org.example.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.ImmutableMap;
import org.example.dto.*;
import org.example.entity.SysUser;
import org.example.mapper.SysMenuMapper;
import org.example.mapper.SysUserMapper;
import org.example.mapper.SysUserRoleMapper;
import org.example.model.PageBean;
import org.example.utils.JwtUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SysUserService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private JwtUtils jwtUtils;

    // 处理登录
    public Map<String, Object> login(LoginDto loginDto) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("name", loginDto.getUsername());

        // 根据用户名查询用户信息
        SysUser sysUser = sysUserMapper.selectOne(qw);

        // 根据用户信息找到用户，并且密码也是正确的
        if(null != sysUser && passwordEncoder.matches(loginDto.getPassword(), sysUser.getPassword())) {
            // 查到用戶所有的權限列表
            List<String> perms = sysMenuMapper.getPerms(sysUser.getName());
            // 生成一个jwt, 并返回
//            String jwt = jwtUtils.generateJwt(sysUser.getName());
            String jwt = jwtUtils.generateJwt(sysUser.getName(), perms);
            return ImmutableMap.of("code", 1, "msg", "success", "access_token", jwt);
        }else {
            // 用户名或者密码错误
            return ImmutableMap.of("code", -1, "msg", "用户名或者密码错误");
        }
    }

    //渲染用户管理数据
    public PageBean<SysUser> getPageData(Integer page, Integer size,String name,String email,String mobile) {
        Page<SysUser> userPage = PageHelper.startPage(page, size);
        sysUserMapper.getAll(name, email, mobile);
        return PageBean.<SysUser>builder()
                .data(userPage.getResult())
                .total(userPage.getTotal())
                .current(userPage.getPageNum())  // 当前页
                .build();
    }

    //删除数据
    public void delete(Integer id){
        sysUserMapper.deleteById(id);
        sysUserRoleMapper.deleteRoleByUserId(id);
    }

    //编辑数据
    public void editUser(EditUserDto editUserDto){
        Integer userId = editUserDto.getId();
        List<Integer> ids = editUserDto.getRoleIds();
        SysUser sysUser = SysUser.builder()
                .id(userId)
                .name(editUserDto.getName())
                .mobile(editUserDto.getMobile())
                .email(editUserDto.getEmail())
                .deptId(editUserDto.getDeptId())
                .lastUpdateTime(new Date())
                .lastUpdateBy(editUserDto.getLastUpdateBy())
                .build();
        sysUserMapper.updateById(sysUser);
        sysUserRoleMapper.deleteRoleByUserId(editUserDto.getId());
        sysUserRoleMapper.batchInsertUserRole(userId,ids);

    }

    //改变状态
    public void getStatus(Integer id) {
        sysUserMapper.getStatus(id);
    }

    //回显操作
    public EditUserDto getById(Integer id){
        SysUser sysUser = sysUserMapper.selectById(id);
        List<Integer> roles = sysUserRoleMapper.getRolesByUserId(id);
        EditUserDto editUser = EditUserDto.builder()
                .id(sysUser.getId())
                .name(sysUser.getName())
                .email(sysUser.getEmail())
                .mobile(sysUser.getMobile())
                .deptId(sysUser.getDeptId())
                .roleIds(roles)
                .build();
        return editUser;
    }

    //添加数据
    public void addUser(AddUserDto addUserDto){
        SysUser sysUser = SysUser.builder().createBy(addUserDto.getCreateBy())
                .email(addUserDto.getEmail())
                .name(addUserDto.getName())
                .mobile(addUserDto.getMobile())
                .createTime(new Date())
                .lastUpdateBy(addUserDto.getCreateBy())
                .status(true)
                .password("$2a$10$RdFGpy1Covt24E78LcFTTOx.7JK4swTYdcmK19QFDHEsVlAeURTNq")
                .lastUpdateTime(new Date())
                .deptId(addUserDto.getDeptId())
                .build();
        sysUserMapper.insert(sysUser);
        Integer userId = sysUser.getId();
        List<Integer> ids = addUserDto.getRoleIds();
        sysUserRoleMapper.batchInsertUserRole(userId,ids);
    }
}
